<template>
  <view class="statistics">
    <view class="statistics-container">
      <nut-tabs
        v-model="activeTab"
        :swipeable="true"
        @change="changeTab"
      >
        <nut-tab-pane
          v-for="tab in tabs"
          :key="tab.id"
          :title="tab.title"
        >
          <view class="statistics-item">
            <view class="calendar">
              <view class="calendar-title">
                <view class="calendar-title-left">
                  <text>{{ titleDate }}</text>
                  <text>回到今天</text>
                </view>
                <view class="calendar-title-right">
                  <view class="day-week-month">
                    <view
                      v-for="(item, index) in dayWeekMonth"
                      :key="index"
                      class="right-item"
                      :class="{ active: tabsDate === index }"
                      @click="handletabsDate(index)"
                      ><text>{{ item }}</text></view
                    >
                  </view>
                </view>
              </view>
              <view class="calendar-content">
                <!-- 日 -->
                <nut-calendar-card
                  v-if="tabsDate == 0"
                  v-model="dayValue"
                  @change="onChange"
                  :style="{ height: calendarHeight }"
                  @page-change="handlePageChangeDebounced"
                  type="single"
                >
                  <template #bottom="{ day }">
                    <view class="status">
                      <i
                        v-if="shouldShowIcon(day.year + '-' + day.month + '-' + day.date)"
                        class="iconfont icon-yuandianfengefu"
                        :style="{ color: getIconColor(day.year + '-' + day.month + '-' + day.date) }"
                      ></i>
                    </view>
                  </template>
                </nut-calendar-card>
                <!-- 周 -->
                <nut-calendar-card
                  v-if="tabsDate == 1"
                  v-model="weekValue"
                  @change="onChange"
                  :style="{ height: calendarHeight }"
                  @page-change="handlePageChangeDebounced"
                  type="week"
                >
                  <template #bottom="{ day }">
                    <view class="status">
                      <i
                        v-if="shouldShowIcon(day.year + '-' + day.month + '-' + day.date)"
                        class="iconfont icon-yuandianfengefu"
                        :style="{ color: getIconColor(day.year + '-' + day.month + '-' + day.date) }"
                      ></i>
                    </view>
                  </template>
                </nut-calendar-card>
                <!-- 月 -->
                <nut-calendar-card
                  v-if="tabsDate == 2"
                  v-model="monthValue"
                  :style="{ height: calendarHeight }"
                  @page-change="click3"
                  type="range"
                >
                  <template #bottom="{ day }">
                    <view class="status">
                      <i
                        v-if="shouldShowIcon(day.year + '-' + day.month + '-' + day.date)"
                        class="iconfont icon-yuandianfengefu"
                        :style="{ color: getIconColor(day.year + '-' + day.month + '-' + day.date) }"
                      ></i>
                    </view>
                  </template>
                </nut-calendar-card>
                <view class="calendar-content-bottom">
                  <nut-divider
                    :style="{
                      color: '#E3E3E3',
                      borderColor: '#E3E3E3',
                      transform: isCalendarFolded ? 'rotate(0deg)' : 'rotate(180deg)',
                    }"
                  >
                    <i
                      class="iconfont icon-xiajiantou"
                      @click="handleCalendarFold"
                    ></i>
                  </nut-divider>
                </view>
                <view class="check-in-record">
                  <view class="check-in-record-item normal">
                    <i class="iconfont icon-yuandianfengefu"></i>
                    <text>正常打卡</text>
                  </view>
                  <view class="check-in-record-item abnormal">
                    <i class="iconfont icon-yuandianfengefu"></i>
                    <text>异常打卡</text>
                  </view>
                </view>
              </view>
            </view>
            <view class="daily-analysis">
              <view class="daily-analysis-con">
                <view class="daily-analysis-title">
                  <view class="analysis-title-left">
                    <text>{{ tabsDate == 0 ? "当日分析" : tabsDate == 1 ? "周度分析" : "月度分析" }}</text>
                    <text>共1次卡，工时0小时</text>
                  </view>
                  <view
                    class="analysis-title-right"
                    @click="handleToDetail(1)"
                    v-if="activeTab == 0"
                  >
                    <text>团队明细</text>
                    <i class="iconfont icon-youjiantou1"></i>
                  </view>
                  <view
                    class="analysis-title-right"
                    @click="handleToDetail(2)"
                    v-if="activeTab == 1"
                  >
                    <text>打卡明细</text>
                    <i class="iconfont icon-youjiantou1"></i>
                  </view>
                </view>
                <view class="export">
                  <view class="export-con">
                    <view class="export-con-left">
                      <img
                        src="https://img.alicdn.com/imgextra/i3/1034622205/O1CN01rMf1Lw1S9wO0oGhnU_!!1034622205.png"
                        alt=""
                      />
                      <text>我的当月考勤汇总-导出报表</text>
                    </view>
                    <view class="export-btn">导出</view>
                  </view>
                </view>
                <view
                  class="today-clock-in"
                  v-if="activeTab == 1 && tabsDate == 0"
                >
                  <view class="con-item">
                    <view class="con-item-left">
                      <view class="check-in-time-box">
                        <view class="time">
                          <!-- active 改变状态是否打卡状态 -->
                          <view class="in-time">
                            <view class="check-icon">
                              <text></text>
                              <!--占位-->
                            </view>
                            <view class="in-time-text">
                              <text>上班时间 {{ atendanceRecordData?.startTime }}</text>
                              <nut-tag
                                v-if="false"
                                color="#EEF4FF"
                                text-color="#1E74FD"
                                >缺卡</nut-tag
                              >
                            </view>
                          </view>
                          <!-- 外勤 -->
                          <view
                            class="check-field-personnel"
                            v-if="false"
                          >
                            <text> 右滑可切换至外勤打卡 </text>
                          </view>
                          <!-- 缺卡 -->
                          <view
                            class="check-miss"
                            v-if="false"
                          >
                            <text>申请纠正<i class="iconfont icon-youjiantou1"></i></text>
                          </view>
                          <!-- 正常打卡时间 -->
                          <view
                            class="check-time"
                            v-if="true"
                          >
                            <view class="check-time-text">
                              <text>打卡时间 {{ atendanceRecordData?.checkInTime?.substring(11, 16) }}</text>
                              <nut-tag
                                :color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.color"
                                :text-color="attendanceStatusColor[atendanceRecordData?.attendanceStatus]?.textColor"
                                >{{ checkStatusList[atendanceRecordData?.attendanceStatus]?.dictLabel }}
                              </nut-tag>
                            </view>
                            <view class="check-adress">
                              <i class="iconfont icon-wifi"></i>
                              <text>{{ atendanceRecordData?.wifiName }}</text>
                            </view>
                            <!-- 请假 -->
                            <view class="leave"></view>
                          </view>
                        </view>
                        <view class="time">
                          <!-- active 改变状态是否打卡状态 -->
                          <view class="in-time active">
                            <view class="check-icon">
                              <text></text>
                            </view>
                            <text class="in-time-text">下班时间 {{ atendanceRecordData?.endTime }}</text>
                          </view>
                          <!-- 外勤 -->
                          <view
                            class="check-field-personnel"
                            v-if="false"
                          ></view>
                          <!-- 正常打卡时间 -->
                          <view
                            class="check-time"
                            v-else
                          >
                            <view class="check-time-text">
                              <text>打卡时间 {{ atendanceRecordData?.checkOutTime?.substring(11, 16) }}</text>
                              <nut-tag
                                :color="attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.color"
                                :text-color="attendanceStatusColor[atendanceRecordData?.attendanceOutStatus]?.textColor"
                                >{{ checkStatusList[atendanceRecordData?.attendanceOutStatus]?.dictLabel }}
                              </nut-tag>
                            </view>
                            <view class="check-adress">
                              <i class="iconfont icon-dingwei1"></i>
                              <text>{{ atendanceRecordData?.wifiName }}</text>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view
                  class="semi-circle-container"
                  v-else
                >
                  <ec-canvas
                    id="checkInChart"
                    canvas-id="checkInChart"
                    ref="checkInChartRef"
                    :ec="ecp"
                  />
                  <view class="check-in-total">
                    <view class="check-in-total-item">
                      <view class="check-in-total-text">
                        <text>3</text>
                        <text>迟到/次</text>
                      </view>
                      <view class="check-in-total-text">
                        <text>3</text>
                        <text>早退/次</text>
                      </view>
                      <view class="check-in-total-text">
                        <text>3</text>
                        <text>缺卡/次</text>
                      </view>
                      <view class="check-in-total-text">
                        <text>3</text>
                        <text>旷工/次</text>
                      </view>
                    </view>
                  </view>
                  <nut-divider :style="{ color: '#f5f5f5' }" />
                </view>
                <view class="false-attendance-statistics">
                  <view class="attendance-statistics-title">
                    <text>假勤统计</text>
                  </view>
                  <view class="attendance-statistics-item">
                    <view class="attendance-statistics-text">
                      <text>3</text>
                      <text>请假/次</text>
                    </view>
                    <view class="attendance-statistics-text">
                      <text>3</text>
                      <text>外出/次</text>
                    </view>
                    <view class="attendance-statistics-text">
                      <text>3</text>
                      <text>出差/次</text>
                    </view>
                    <view class="attendance-statistics-text">
                      <text>3</text>
                      <text>外勤/次</text>
                    </view>
                  </view>
                </view>
              </view>
              <view class="check-in-work-overtime">
                <view class="work-overtime-item">
                  <view class="work-overtime-title">
                    <text>加班统计</text>
                  </view>
                  <view class="work-overtime-text">
                    <text>累计20小时</text>
                    <i class="iconfont icon-youjiantou1"></i>
                  </view>
                </view>
                <view class="work-overtime-item">
                  <view class="work-overtime-title">
                    <text>外出打卡/次</text>
                  </view>
                  <view class="work-overtime-text">
                    <i class="iconfont icon-youjiantou1"></i>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="addTask-bottom">
            <view class="addTask-bottom-logo">
              <img
                src="https://img.alicdn.com/imgextra/i2/1034622205/O1CN01ROtCca1S9wNLeJ6zx_!!1034622205.png"
                alt=""
              />
            </view>
          </view>
        </nut-tab-pane>
      </nut-tabs>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { navigateTo } from "@tarojs/taro";
import * as echarts from "@/libs/wechat/components/ec-canvas/echarts.min";
import { loadEcharts } from "echarts4taro3";

import Taro from "@tarojs/taro";
import { times, formatDates, debounce, getCurrentWeekRange } from "@/utils/utils";
import {
  getAttendanceRecordQueryData,
  getDictDataTypeList,
  getAttendanceRecordQueryDetailList,
  getAttendanceRecordQueryStatistics,
} from "@/api/index";
import { userInfoStore } from "@/stores/userInfoStore";
import { formatDateMonths } from "@/utils/utils";
const { startDate, endDate } = getCurrentWeekRange();
const store = userInfoStore();
const atendanceRecordData = ref(); // 考勤记录当天
const atendanceRecordDataList = ref(); // 考勤记录列表
const checkStatusList = ref([]); // 考勤状态列表
const titleDate = ref("");
const calendarKey = ref(0); // 强刷
const tabs = ref([
  { id: 0, title: "团队统计" },
  { id: 1, title: "我的统计" },
]);
const activeTab = ref(0);
const checkInChartRef = ref<any>(null); //
const attendanceStatusColor = ref([
  {
    color: "#EEF4FF",
    textColor: "#1E74FD",
  },
  {
    color: "#FFF3E3",
    textColor: "#FF8000",
  },
  {
    color: "#FEECEC",
    textColor: "#E90800",
  },
  {
    color: "#F0F0F0",
    textColor: "#666",
  },
]);
const tabsDate = ref(0);
const dayWeekMonth = ref(["日", "周", "月"]);
const dayValue = ref(new Date());
const weekValue = ref([new Date(startDate), new Date(endDate)]);
const monthValue = ref(); //默认当月选中
// const dateValue = ref();
const isCalendarFolded = ref(false); // 新增：控制折叠状态
const ecp = ref({
  onInit: async (canvas: any, width: number, height: number) => {
    await loadEcharts(echarts);
    const chart = echarts.init(canvas, null, {
      width,
      height,
      devicePixelRatio: 2,
    });
    // 3. 必须设置canvas图表关联
    canvas.setChart(chart);
    // 4. 设置图表配置
    var option;
    option = {
      title: {},
      series: [
        {
          type: "pie",
          silent: true, // 禁用交互
          label: {
            position: "center",
            distance: -10,
            formatter: function (params) {
              return "{a|" + "21/3" + "}\n{b|正常天数/异常天数}";
            },
            rich: {
              a: {
                fontSize: 24,
                fontWeight: "bold",
                color: "#333",
                lineHeight: 30,
              },
              b: {
                fontSize: 14,
                color: "#666",
                lineHeight: 20,
              },
            },
          },
          center: ["50%", "50%"],
          radius: ["60%", "70%"],
          startAngle: 180,
          avoidLabelOverlap: false,
          itemStyle: {
            borderWidth: 0,
            borderColor: "transparent",
          },
          data: [
            {
              name: "用量",
              // value: urgentTask.value?.completionRatio, // 改为82.5%以匹配图片
              value: 22, // 改为82.5%以匹配图片
              itemStyle: {
                color: "#1E74FD",
                // 使用阴影实现平滑的圆弧效果
                shadowColor: "#1E74FD",
                // shadowBlur: 4,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                borderRadius: [20, 20, 20, 20], // 上左、上右圆角
              },
            },
            {
              name: "rest",
              // value: 100 - urgentTask.value?.completionRatio, // 100-82.5
              value: 100 - 22, // 100-82.5
              itemStyle: {
                color: "#E2E7E6",
                // 使用阴影实现平滑的圆弧效果
                shadowColor: "#E2E7E6",
                // shadowBlur: 4,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                borderRadius: [0, 20, 0, 20], // 下右、下左圆角
              },
            },
            {
              name: "bottom",
              value: 100,
              itemStyle: {
                color: "transparent",
              },
            },
          ],
        },
      ],
    };
    option && chart.setOption(option);
    return chart;
  },
});
const dateFlagMap = ref();
watch(
  () => atendanceRecordDataList.value, // 改为getter函数形式
  newVal => {
    const map: Record<string, boolean> = {};
    atendanceRecordDataList.value?.forEach(item => {
      if (item.workDate) {
        const dateKey = item.workDate.split(" ")[0];
        map[dateKey] = item.flag;
      }
    });
    dateFlagMap.value = map;
    console.log("Updated dateFlagMap:", map); // 调试日志
  },
  { deep: true, immediate: true }, // 改为immediate: true
);
onMounted(async () => {
  await handleGetAttendanceQueryData();
  getDictMeetingPurviewFun("check_status");
  titleDate.value = formatDateMonths(new Date());

   handleAttendanceQueryStatistics();
});

// 选择正月
const click3 = () => {
  const d = new Date();
  const year = d.getFullYear();
  let month = d.getMonth() + 1;
  month = month < 10 ? "0" + month : month + "";
  const yearMonth = `${year}-${month}`;
  const currMonthDays = getMonthDays(year + "", month + "");
  monthValue.value = [new Date(`${yearMonth}-01`), new Date(`${yearMonth}-${currMonthDays}`)];
  console.log(`${yearMonth}-01`, `${yearMonth}-${currMonthDays}`);
};
const isLeapYear = function (y) {
  return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
};
const getMonthDays = function (year, month) {
  if (/^0/.test(month)) {
    month = month.split("")[1];
  }
  return [0, 31, isLeapYear(Number(year)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
// 字典获取
const getDictMeetingPurviewFun = async dictType => {
  await getDictDataTypeList(dictType).then(res => {
    if (dictType == "check_status") {
      checkStatusList.value = res.data;
    }
  });
};
//
const handleAttendanceQueryStatistics = async () => {
  let params = {
    userId: Taro.getStorageSync("user").userId,
    startDate: "2025-06-01",
    endDate: "2025-06-30",
  };
  await getAttendanceRecordQueryStatistics(params).then(res => {
    console.log(res.data, "res.data");
  });
};
// 获取每一天的打卡明细
const handleGetAttendanceRecordQueryDetailList = async (date: string) => {
  let params = {
    dataDate: date,
  };
  await getAttendanceRecordQueryDetailList(params).then(res => {
    atendanceRecordDataList.value = res.data;
  });
};
// 检查是否应该显示图标
const shouldShowIcon = (dateObj: Date) => {
  if (!dateFlagMap.value) return false;
  const dateStr = formatDates(dateObj);
  return dateStr in dateFlagMap.value;
};
// 获取图标颜色（可根据flag或其他状态返回不同颜色）
const getIconColor = dateObj => {
  const dateStr = formatDates(dateObj);
  const item = atendanceRecordDataList.value?.find(item => item.workDate && item.workDate.startsWith(dateStr));
  return item?.flag ? "#1e74fd" : "#ff4d4f"; // 绿色表示正常，红色表示异常
};
// 获取当日打卡记录
const handleGetAttendanceQueryData = async () => {
  let params = {
    userId: Taro.getStorageSync("user").userId,
    date: formatDates(new Date()),
  };
  await getAttendanceRecordQueryData(params).then(res => {
    atendanceRecordData.value = res.data;
    store.punchCards = res.data;
  });
};
// 计算日历高度
const calendarHeight = computed(() => {
  return isCalendarFolded.value ? "300rpx" : "720rpx"; // 根据需求调整高度值
});
//切换tab
const changeTab = (val: number) => {
  console.log(val);
  console.log(activeTab.value);
};
const onChange = (val: Date) => {
  console.log(val);
  console.log(weekValue.value, "weekValue");
};
const handleMonthChange = async (val: Date) => {
  titleDate.value = val.year + "年" + (val.month <= 9 ? "0" : "") + val.month + "月";
  console.log(titleDate.value, "yue");
  let date = val.year + "-" + (val.month <= 9 ? "0" : "") + val.month;
  await handleGetAttendanceRecordQueryDetailList(date);
};

// 获取当前日期
const handlePageChangeDebounced = debounce(handleMonthChange, 300);
const handletabsDate = (index: number) => {
  calendarKey.value++; // 修改key值会强制组件重新创建
  tabsDate.value = index;
  console.log(dayValue.value, "dayValue.value");
  console.log(weekValue.value, "weekValue.value");
};
const handleCalendarFold = () => {
  isCalendarFolded.value = !isCalendarFolded.value;
  console.log("日历折叠状态:", isCalendarFolded.value);
};
const handleToDetail = (type: number) => {
  navigateTo({
    url: "/packageC/pages/checkInDetails/index?isDetailType=" + type,
  });
};
</script>

<style lang="less">
@import url("./index.less");
</style>
